package com.chen.tliaswebtest.service.impl;

import com.chen.tliaswebtest.exception.TliasException;
import com.chen.tliaswebtest.mapper.EmpMapper;
import com.chen.tliaswebtest.pojo.User;
import com.chen.tliaswebtest.service.LogInService;
import com.chen.tliaswebtest.utils.JwtUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author chen
 * @version 1.0
 * @create_date 2025/7/25
 * 登录服务实现类
 */
@Service
// 这里只有查询操作，不需要事务
// @Transactional
public class LogInServiceImpl implements LogInService {
    private final EmpMapper empMapper;

    public LogInServiceImpl(EmpMapper empMapper) {
        this.empMapper = empMapper;
    }

    @Override
    public User logIn(User user) {
        User resultUser = empMapper.login(user.getUsername(), user.getPassword());
        if (resultUser == null) {
            throw new TliasException("用户名或密码错误！");
        }
        // 添加JWT令牌生成的token
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", resultUser.getId());
        claims.put("username", resultUser.getUsername());
        resultUser.setToken(JwtUtils.generateJwt(claims));
        return resultUser;
    }
}
